from flask import Flask, render_template, request
from utils import browser_views
from spider import Spider_baidu_image
from func_class import check_data
import config
import langid
import os

app = Flask(__name__)


@app.route("/", methods=["GET", "POST"])
def index():
    browser_view = browser_views(config.index_route)
    return render_template("index.html", browser_view=browser_view)


@app.route("/<user_id>", methods=["GET", "POST"])
def index2(user_id):
    if not user_id:
        return render_template("index.html")
    return render_template("index.html", user_name=user_id)


@app.route('/login', methods=["GET", "POST"])
def login():
    browser_view = browser_views(config.login_route)
    return render_template("login.html", browser_view=browser_view)


@app.route('/register', methods=["GET", "POST"])
def register():
    browser_view = browser_views(config.register_route)
    return render_template("register.html", browser_view=browser_view)


@app.route('/user', methods=["GET", "POST"])
def login2():
    user_name = request.form["user_name"]
    user_password = request.form["user_password"]
    with open(config.user_info_route, encoding='utf-8') as f:
        user_info = eval(f.read())
    try:
        if user_password == user_info[user_name]:
            browser_view = browser_views(config.index_route)
            return render_template("index.html", user_name=user_name, browser_view=browser_view)
        else:
            browser_view = browser_views(config.login_error_route)
            return render_template("login_error.html", browser_view=browser_view)
    except:
        browser_view = browser_views(config.login_error_route)
        return render_template("login_error.html", browser_view=browser_view)


@app.route("/input")
def render_input1():
    browser_view = browser_views(config.permission_error_route)
    return render_template("permission_error.html", browser_view=browser_view)


@app.route("/personal_center")
def render_personal_center1():
    browser_view = browser_views(config.permission_error_route)
    return render_template("permission_error.html", browser_view=browser_view)


@app.route("/language_classification")
def render_language_classification():
    browser_view = browser_views(config.permission_error_route)
    return render_template("permission_error.html", browser_view=browser_view)


@app.route("/<user_id>/input")
def render_input(user_id):
    if not user_id:
        browser_view = browser_views(config.permission_error_route)
        return render_template("permission_error.html", browser_view=browser_view)
    browser_view = browser_views(config.input_route)
    return render_template("input.html", user_name=user_id, browser_view=browser_view)


@app.route("/<user_id>/input_chinese")
def render_input_chinese(user_id):
    if not user_id:
        browser_view = browser_views(config.permission_error_route)
        return render_template("permission_error.html", browser_view=browser_view)
    browser_view = browser_views(config.input_chinese_route)
    return render_template("input_chinese.html", user_name=user_id, browser_view=browser_view)


@app.route("/<user_id>/check_data")
def render_check_input(user_id):
    if not user_id:
        browser_view = browser_views(config.permission_error_route)
        return render_template("permission_error.html", browser_view=browser_view)
    browser_view = browser_views(config.input_check_data_route)
    return render_template("input_check_data.html", user_name=user_id, browser_view=browser_view)


@app.route("/<user_id>/personal_center")
def render_personal_center(user_id):
    if not user_id:
        browser_view = browser_views(config.permission_error_route)
        return render_template("permission_error.html", browser_view=browser_view)
    browser_view = browser_views(config.personal_center_route)
    return render_template("personal_center.html", user_name=user_id, browser_view=browser_view)


@app.route("/<user_id>/doData", methods=["post"])
def hand_post(user_id):
    if not user_id:
        browser_view = browser_views(config.permission_error_route)
        return render_template("permission_error.html", browser_view=browser_view)
    input_data = request.form["input_data"]
    all_words = request.form["all_words"]
    brand_words = request.form["brand_words"]
    areas_words = request.form["areas_words"]
    datas = []
    for j in [input_data, all_words, brand_words, areas_words]:
        strs = ''
        data = []
        for i in j:
            if i != '\n':
                strs += i
            else:
                strs = strs.replace('\r', '').strip()
                data.append(strs)
                strs = ''
        if strs != '':
            data.append(strs)
        datas.append(data)

    input_data = datas[0]
    all_words = datas[1]
    brand_words = datas[2]
    areas_words = datas[3]

    #  从输入的数据中刷选出有效数据和无效数据
    new_data = []
    invalid_data = []
    for i in input_data:
        x_list = [x for x in i.split() if x not in all_words]
        if len(x_list) == len(i.split()):
            new_data.append(i)
        else:
            invalid_data.append(i)

    #  从有效数据中筛选出包含品牌词的单词和不包含品牌词的单词
    brand_data = []
    new_data2 = []
    for i in new_data:
        y_list = [y for y in i.split() if y in brand_words]
        if len(y_list) > 0:
            brand_data.append(i)
        else:
            new_data2.append(i)

    #  从不包含品牌词的数据中筛选出包含地域的词和剩余的其它词
    areas_data = []
    other_data = []
    for i in new_data2:
        z_list = [z for z in i.split() if z in areas_words]
        if len(z_list) > 0:
            areas_data.append(i)
        else:
            other_data.append(i)

    data_dict = dict(
        all_words=all_words,
        invalid_data=invalid_data,
        brand_data=brand_data,
        areas_data=areas_data,
        other_data=other_data
    )
    browser_view = browser_views(config.output_route)
    return render_template("output.html", **data_dict, user_name=user_id, browser_view=browser_view)


@app.route("/<user_id>/do_chinese_data", methods=["post"])
def hand_post_chinese(user_id):
    if not user_id:
        browser_view = browser_views(config.permission_error_route)
        return render_template("permission_error.html", browser_view=browser_view)
    input_data = request.form["input_data"]
    input_brand = request.form["brand_words"]

    datas = []
    for j in [input_data, input_brand]:
        strs = ''
        data = []
        for i in j:
            if i != '\n':
                strs += i
            else:
                strs = strs.replace('\r', '').strip()
                data.append(strs)
                strs = ''
        if strs != '':
            data.append(strs)
        datas.append(data)
    input_data_list = datas[0]
    input_brand_list = datas[1]

    brand_datas = []
    for i in input_data_list:
        for j in input_brand_list:
            if j in i:
                brand_datas.append(i)
                break

    others_data = set(input_data_list) - set(brand_datas)

    data_dict = dict(
        input_data=input_data_list,
        input_brand=input_brand_list,
        brand_datas=brand_datas,
        others_data=others_data
    )
    browser_view = browser_views(config.output_chinese_route)
    return render_template("output_chinese.html", **data_dict, user_name=user_id, browser_view=browser_view)


@app.route("/video")
def render_video():
    browser_view = browser_views(config.video_route)
    return render_template("video.html", browser_view=browser_view)


@app.route("/<user_id>/language_classification", methods=["get", "post"])
def hand_language(user_id):
    if not user_id:
        browser_view = browser_views(config.permission_error_route)
        return render_template("permission_error.html", browser_view=browser_view)
    if request.method == 'POST':
        language_data = request.form["language_data"]
        language_data = [i for i in language_data.split('\n')]

        #  定义多个国家列表
        chinese = []
        tuerqi = []
        english = []
        yuenanyu = []
        fayu = []
        deyu = []
        xibanya = []
        riyu = []
        eyu = []
        taiyu = []
        alaboyu = []
        others = []
        malatiyu = []  # 马拉提语
        ruidian = []  # 瑞典
        baojialiyayu = []  # 保加利亚语
        wukelanyu = []  # 乌克兰语
        aokeyu = []  # 奥克语
        yindiyu = []  # 印地语
        niboeryu = []  # 尼泊尔语
        xiongyaliyu = []  # 匈牙利语
        putaoyayu = []  # 葡萄牙语
        nuoweiyu = []  # 挪威语

        #  对多个国家语言分类
        for i in language_data:
            language = langid.classify(i)[0]
            if language == 'zh':
                chinese.append(i)
            elif language == 'tr':
                tuerqi.append(i)
            elif language == 'en':
                english.append(i)
            elif language == 'vi':
                yuenanyu.append(i)
            elif language == 'fr':
                fayu.append(i)
            elif language == 'de':
                deyu.append(i)
            elif language == 'es':
                xibanya.append(i)
            elif language == 'ja':
                riyu.append(i)
            elif language == 'ru':
                eyu.append(i)
            elif language == 'th':
                taiyu.append(i)
            elif language == 'ar':
                alaboyu.append(i)
            elif language == 'mr':
                malatiyu.append(i)
            elif language == 'sv':
                ruidian.append(i)
            elif language == 'bg':
                baojialiyayu.append(i)
            elif language == 'uk':
                wukelanyu.append(i)
            elif language == 'oc':
                aokeyu.append(i)
            elif language == 'hi':
                yindiyu.append(i)
            elif language == 'ne':
                niboeryu.append(i)
            elif language == 'hu':
                xiongyaliyu.append(i)
            elif language == 'pt':
                putaoyayu.append(i)
            elif language == 'no' or language == 'nn' or language == 'nb':
                nuoweiyu.append(i)
            else:
                others.append([i, language])

        #  将数据打包发送到前端
        data_dict = dict(
            chinese=chinese,
            tuerqi=tuerqi,
            english=english,
            yuenanyu=yuenanyu,
            fayu=fayu,
            xibanya=xibanya,
            deyu=deyu,
            riyu=riyu,
            eyu=eyu,
            taiyu=taiyu,
            alaboyu=alaboyu,
            aokeyu=aokeyu,
            malatiyu=malatiyu,
            ruidian=ruidian,
            baojialiyayu=baojialiyayu,
            wukelanyu=wukelanyu,
            yindiyu=yindiyu,
            niboeryu=niboeryu,
            xiongyaliyu=xiongyaliyu,
            putaoyayu=putaoyayu,
            nuoweiyu=nuoweiyu,
            others=others
        )
        browser_view = browser_views(config.language_classification_route)
        return render_template("language_classification.html", **data_dict, user_name=user_id, browser_view=browser_view)
    else:
        browser_view = browser_views(config.language_classification_route)
        return render_template("language_classification.html", user_name=user_id, browser_view=browser_view)


@app.route("/spider", methods=["GET", "POST"])
def render_spider():
    browser_view = browser_views(config.spider_route)
    if request.method == 'POST':
        spider_name = request.form["spider_name"]
        spider_page = request.form["spider_page"]
        cwd = os.getcwd()
        base_name = os.path.join(cwd, 'spider')
        file_name = os.path.join(base_name, spider_name)
        spider = Spider_baidu_image(spider_name, spider_page)
        spider()
        return render_template("download.html", file_name=file_name, browser_view=browser_view)
    else:
        return render_template("spider.html", browser_view=browser_view)


@app.route("/<user_id>/check_data", methods=["post"])
def check_post(user_id):
    if not user_id:
        browser_view = browser_views(config.permission_error_route)
        return render_template("permission_error.html", browser_view=browser_view)
    value_data = request.form["value_data"]
    no_value_data = request.form["no_value_data"]
    datas = []
    for j in [value_data, no_value_data]:
        strs = ''
        data = []
        for i in j:
            if i != '\n':
                strs += i
            else:
                strs = strs.replace('\r', '').strip()
                data.append(strs)
                strs = ''
        if strs != '':
            data.append(strs)
        datas.append(data)

    value_data = datas[0]
    no_value_data = datas[1]
    set_origin_data, value_words, no_value_words = check_data(value_data, no_value_data)
    data_len = [len(value_data), len(no_value_data), len(set_origin_data), len(value_words), len(no_value_words)]
    #  将数据打包发送到前端
    data_dict = dict(
        value_data=value_data,
        no_value_data=no_value_data,
        set_origin_data=set_origin_data,
        value_words=value_words,
        no_value_words=no_value_words
    )
    browser_view = browser_views(config.output_check_data_route)
    return render_template("output_check_data.html", **data_dict, data_len=data_len, user_name=user_id, browser_view=browser_view)


# app.run()
app.run(host="0.0.0.0", port=54321, debug=True)
